import axios from 'axios'
import _ from 'lodash'
import router from '../router/index'
import store from '@/store'
import config from '@/config'
const requests = []

export default (Vue) => {
    Object.defineProperties(Vue.prototype, {
            $http: {
                value: axios
            }
        })
    //axios配置
    axios.defaults.baseURL = config[process.env.NODE_ENV].host
  //  console.log(process.env.NODE_ENV,'process.env.NODE_ENV')
    axios.defaults.timeout = 10000
    axios.defaults.withCredentials = true
    axios.defaults.headers['Content-Type'] = 'text/plain; charset=utf-8'
        // 添加拦截器
    axios.interceptors.request.use(function(config) {
        store.dispatch('setLoading', true)
        console.log(config)   
        requests.push(config)
        return config
    }, function(error) {
        store.dispatch('setLoading', false)
        return Promise.reject(error)
    })

    axios.interceptors.response.use(function(response) {
     
        _.remove(requests, r => {
            return r === response.config
        })

        if (!requests.length) {
       
            setTimeout(() => {
                store.dispatch('setLoading', false)
            }, 100)
        }
        
        //未登录处理
        if (response.data.code!=0) {
            if (response.data.code == '1000') {
               // router.push('/login?go=1')
            }
            return Promise.reject(response.data)
        }

        return response.data
    }, function(error) {
        store.dispatch('setLoading', false)
        Loading.close()
        if (error.response) {
            console.log(error.response.status)
            switch (error.response.status) {
                case 401:
                    console.log('401 未授权')
                    break
                case 500:
                    console.log('500')
                    break
                default:
                    console.log('发生错误了')
            }
        } else {
           
        }
        return Promise.reject(error)
    })
}